<template>
  <page-header-wrapper>
    <div class="table-page-search-wrapper">
      <a-card>
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :xl="6" :lg="8" :md="12" :xs="24">
              <a-form-item label="所属社区">
                <a-cascader :options="community" :default-value="[null]"
                            :field-names="{ label: 'name', value: 'id',children:'children' }" :allowClear="false"
                            @change="onCommunityChange"/>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="8" :md="12" :xs="24">
              <a-form-item label="商家手机号">
                <a-input v-model="search.phone" :allowClear="true"></a-input>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="8" :md="12" :xs="24">
              <a-form-item label="每页条数">
                <a-select :default-value="5" @change="handlePageSize">
                  <a-select-option :value="value" v-for="value in pageSizeSelect" :key="value">
                    {{value}}条/页
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="8" :md="12" :xs="24">
              <a-button type="primary" @click="handleTableChange">查询</a-button>
            </a-col>
          </a-row>
          <a-row :gutter="[48,8]">
            <a-col :md="12" :sm="24">
              <a-form-item label="批量导入">
                <a-row :gutter="[48,8]">
                  <a-col :lg="12" :md="24">
                    <a-button type="primary" @click="getMarketTemplate">获取导入模板</a-button>
                  </a-col>
                  <a-col :lg="12" :md="24">
                    <a-upload
                      name="file"
                      :multiple="false"
                      :before-upload="uploadMarketTemplate"
                      :preview-file="()=>{}"
                      :showUploadList="false"
                    >
                      <a-button type="primary">上传模板文件</a-button>
                    </a-upload>
                  </a-col>
                </a-row>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24">
              <a-form-item label="操作">
                <a-row type="flex" :gutter="[48,8]">
                  <a-col :xl="6" :lg="8" :md="12" :xs="24">
                    <a-button type="primary" @click="preToNewMarket">新建</a-button>
                  </a-col>
                  <a-modal
                    v-model="newMarketState.state"
                    title="添加商家"
                    @ok="toNewMarket"
                  >
                    <a-card>
                      <a-form layout="inline">
                        <a-row>
                          <a-col>
                            <a-form-item label="店名" style="width: 100%" :label-col=" { span: 4,offset:2 }"
                                         :wrapper-col="{ span: 16 }">
                              <a-input style="width: 100%" v-model="newMarketState.marketInfo.name"
                              ></a-input>
                            </a-form-item>
                          </a-col>
                          <a-col>
                            <a-form-item label="联系人" style="width: 100%" :label-col=" { span: 4,offset:2 }"
                                         :wrapper-col="{ span: 16 }">
                              <a-input style="width: 100%" v-model="newMarketState.marketInfo.contacts"
                              ></a-input>
                            </a-form-item>
                          </a-col>
                          <a-col>
                            <a-form-item label="手机号" style="width: 100%" :label-col=" { span: 4,offset:2 }"
                                         :wrapper-col="{ span: 16 }">
                              <a-input style="width: 100%" v-model="newMarketState.marketInfo.phone"
                                       :max-length="11"></a-input>
                            </a-form-item>
                          </a-col>
                          <a-col>
                            <a-form-item label="地址" style="width: 100%" :label-col=" { span: 4,offset:2 }"
                                         :wrapper-col="{ span: 16 }">
                              <a-input style="width: 100%" v-model="newMarketState.marketInfo.address"
                              ></a-input>
                            </a-form-item>
                          </a-col>
                          <a-col>
                            <a-form-item label="类型" style="width: 100%" :label-col=" { span: 4,offset:2 }"
                                         :wrapper-col="{ span: 16 }">
                              <a-cascader :options="marketType" :default-value="[null]"
                                          :field-names="{ label: 'name', value: 'id',children:'children' }"
                                          :allowClear="true" @change="changeAddMarketType"/>
                            </a-form-item>
                          </a-col>
                          <a-col>
                            <a-form-item label="所属社区" style="width: 100%" :label-col=" { span: 4,offset:2 }"
                                         :wrapper-col="{ span: 16 }">
                              <a-cascader :options="marketCommunity"
                                          :default-value="[null]"
                                          :field-names="{ label: 'name', value: 'id',children:'children' }"
                                          :allowClear="true" @change="onAddCommunityChange"/>
                            </a-form-item>
                          </a-col>
                        </a-row>
                      </a-form>
                    </a-card>
                  </a-modal>
                  <a-col :xl="6" :lg="8" :md="12" :xs="24">
                    <a-button type="primary" :disabled="!hasSelected" @click="allActive">启用</a-button>
                  </a-col>
                  <a-col :xl="6" :lg="8" :md="12" :xs="24">
                    <a-button type="primary" :disabled="!hasSelected" @click="allDisActive">禁用</a-button>
                  </a-col>
                  <a-col :xl="6" :lg="8" :md="12" :xs="24">
                    <a-button type="danger" :disabled="!hasSelected" @click="allDelete">删除</a-button>
                  </a-col>
                </a-row>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>

        <a-table :row-selection="{selectedRowKeys: selection.selectedRowKeys, onChange: onSelectChange}"
                 @change="handleTableChange"
                 :pagination="pagination" :loading="loading" size="small" bordered :data-source="data"
                 :columns="columns" :scroll="{ x: 1650 }">
          <span slot="action" slot-scope="text,record">
              <a-button type="link" @click="lookMarketInfo(record)">查看或修改详情</a-button><a-divider/>
              <a-button type="link" @click="toShowPhoto(record)">查看店铺图片</a-button>
          </span>
          <span slot="pos" slot-scope="text,record">
            {{ record.latitude }},{{ record.longitude }}
          </span>
        </a-table>
        <a-modal
          v-model="updateMarket.state"
          :title="marketModelState.orgInfo.title"
          style="z-index: 9999"
          @ok="toUpdate"
        >
          <a-card>
            <a-form layout="inline">
              <a-row>
                <a-col>
                  <a-form-item label="店铺名" style="width: 100%" :label-col=" { span: 4,offset:2 }"
                               :wrapper-col="{ span: 16 }">
                    <a-input style="width: 100%" v-model="updateMarket.info.name"></a-input>
                  </a-form-item>
                </a-col>
                <a-col>
                  <a-form-item label="店主名" style="width: 100%" :label-col=" { span: 4,offset:2 }"
                               :wrapper-col="{ span: 16 }">
                    <a-input style="width: 100%" v-model="updateMarket.info.contacts"></a-input>
                  </a-form-item>
                </a-col>
                <a-col>
                  <a-form-item label="手机号" style="width: 100%" :label-col=" { span: 4,offset:2 }"
                               :wrapper-col="{ span: 16 }">
                    <a-input style="width: 100%" v-model="updateMarket.info.phone"></a-input>
                  </a-form-item>
                </a-col>
                <a-col>
                  <a-form-item label="社区" style="width: 100%" :label-col=" { span: 4,offset:2 }"
                               :wrapper-col="{ span: 16 }">
                    <a-cascader :options="marketCommunity" :default-value="[updateMarket.info.communityId]"
                                :field-names="{ label: 'name', value: 'id',children:'children' }" :allowClear="false"
                                @change="onUpdateCommunityChange">
                    </a-cascader>
                    <!--                    <a-select-->
                    <!--                      v-model:value="updateMarket.info.communityId"-->
                    <!--                    >-->
                    <!--                      <a-select-option v-for="community in marketCommunity" :key="community.id" :value="community.id">-->
                    <!--                        {{ community.name }}-->
                    <!--                      </a-select-option>-->
                    <!--                    </a-select>-->
                  </a-form-item>
                </a-col>
                <a-col>
                  <a-form-item label="类型" style="width: 100%" :label-col=" { span: 4,offset:2 }"
                               :wrapper-col="{ span: 16 }">
                    <a-cascader :options="marketType" :default-value="[updateMarket.info.typeId]"
                                :field-names="{ label: 'name', value: 'id',children:'children' }" :allowClear="false"
                                @change="onUpdateTypeChange"/>
                  </a-form-item>
                </a-col>
                <a-col>
                  <a-form-item label="描述" style="width: 100%" :label-col=" { span: 4,offset:2 }"
                               :wrapper-col="{ span: 16 }">
                    <a-input style="width: 100%" v-model="updateMarket.info.description"></a-input>
                  </a-form-item>
                </a-col>
                <a-col>
                  <a-form-item label="特色" style="width: 100%" :label-col=" { span: 4,offset:2 }"
                               :wrapper-col="{ span: 16 }">
                    <a-input style="width: 100%" v-model="updateMarket.info.feature"></a-input>
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
          </a-card>
        </a-modal>
        <a-modal v-model="showPhoto.state">
          <img alt="example" style="width: 100%" :src="showPhoto.url"/>
        </a-modal>
      </a-card>
    </div>
  </page-header-wrapper>

</template>

<script>

import {
  addMarket,
  deleteMarket,
  getMarket,
  getMarketTemplate,
  getMarketType, updateMarket,
  uploadMarketTemplate
} from "../../api/market";
import {getCommunity} from "@/api/community";

const columns = [
  {
    dataIndex: 'id',
    title: '店铺ID',
    key: 'id',
    fixed: 'left',
    width: 150
  },
  {
    "dataIndex": "name",
    "title": "店名",
    fixed: 'left',
    width: 150
  },
  {
    "dataIndex": "type.type",
    "title": "类型",
    width: 150
  },
  {
    "dataIndex": "contacts",
    "title": "店主名",
    width: 150
  },
  {
    "dataIndex": "phone",
    "title": "手机号",
    width: 150
  },
  {
    "dataIndex": "user.id",
    "title": "绑定用户ID",
    width: 150
  },
  {
    "dataIndex": "user.nickName",
    "title": "绑定用户用户名",
    width: 150
  },
  {
    "title": "位置",
    scopedSlots: {customRender: 'pos'},
    width: 150
  },
  {
    dataIndex: 'community.name',
    title: '所属社区',
    width: 150
  },
  {
    "dataIndex": "state",
    "title": "用户状态",
    customRender(text, scope) {
      let str = '';
      str += (Number(text) === 1 ? '使用中' : '被禁用')
      return str
    },
  },
  {
    "title": "操作",
    fixed: 'right',
    width: 150,
    scopedSlots: {customRender: 'action'}
  }
]

export default {
  name: "userInfo",
  data() {
    let _this = this;
    return {
      search: {
        phone: '',
        communityId: null
      },
      loading: true,
      pagination: {
        pageSize: 5,
        current: 1,
        total:0
      },
      pageSizeSelect:[
        5,10,20,50,100
      ],
      updateMarket: {
        state: false,
        info: {
          address: "",
          contacts: "魏林",
          description: 'null',
          feature: "[\"餐饮服务\"]",
          id: 3,
          name: "天津自贸试验区新芝莱士快餐店",
          phone: "18622041710",
          typeId: '',
          communityId: ''
        },
        loading: false
      },
      showPhoto: {
        state: false,
        url: ''
      },
      dataSource: [
        {
          value: null,
          label: '全部'
        },
        {
          value: 1,
          label: '社区1'
        },
        {
          value: 2,
          label: '社区2'
        },
        {
          value: 3,
          label: '社区3'
        },
      ],
      data: [
        {
          id: 1
        },
        {
          id: 2
        },
        {
          id: 3
        }
      ],
      selection: {
        selectedRowKeys: [],
        selectedId: [],
      },
      columns: columns,
      marketModelState: {
        state: false,
        id: '',
        orgInfo: {
          title: 'zqa的商店'
        }
      },
      newMarketState: {
        state: false,
        marketInfo: {
          phone: '',
          address: '',
          communityId: '',
          typeId: '',
          contacts: ''
        }
      },
      community: [
        {
          id: null,
          name: '全部'
        }
      ],
      marketCommunity: [],
      marketType: []
    }
  },
  mounted() {
    this.init();
  },
  methods: {
    async handlePageSize(value) {
      this.pagination.pageSize=value;
      await this.handleTableChange();
    },
    async init() {
      await this.searchCommunity()
      await this.searchType()
      await this.handleTableChange({current: 1})
    },
    async handleTableChange(pagination) {
      this.loading = true;

      if (pagination != null) this.pagination.current = pagination.current

      await this.searchMarket();

      this.loading = false;
    },
    async searchType() {
      let _this = this;
      await getMarketType().then((res) => {
        _this.marketType = [];
        res.data.forEach((val) => {
          _this.marketType.push({
            id: val.id,
            name: val.type,
          })
        })
      })
    },
    async searchCommunity() {
      let _this = this;
      await getCommunity({}).then((res) => {
        if (res.status === 200) {
          _this.community = [
            {
              id: null,
              name: '全部'
            },
          ]
          _this.marketCommunity = []
          res.data.forEach((val) => {
            _this.community.push(val)
            _this.marketCommunity.push(val)
          })
        } else {
          _this.$notification.warning({
            message: res.message
          })
        }
      });
    },
    getMarketTemplate() {
      getMarketTemplate();
    },
    toShowPhoto(record) {
      this.showPhoto.url = record.head_img_url;
      if (!(this.showPhoto.url == undefined)) {
        this.showPhoto.state = true
      } else {
        this.$notification.error({
          message: '该店铺暂无图片'
        })
      }
    },
    uploadMarketTemplate(file) {
      let _this = this;
      if (this.search.communityId == null) {
        _this.$notification.error({
          message: '请选择当前社区'
        });
        return false
      }
      console.log(file)
      let form = new FormData();
      form.append('communityId', this.search.communityId);
      form.append('file', file);
      uploadMarketTemplate(form).then((res) => {
        if (res.status === 200) {
          _this.$notification.success({ message: '上传成功' });
        }
      }).catch((res) => {
        _this.$notification.error({
          message:res.message
        });
      }).finally(() => {
        _this.search.phone = ''
        _this.handleTableChange();
      });
      return false
    },
    searchMarket() {
      let _this = this;
      getMarket({
        number: this.pagination.current,
        size: this.pagination.pageSize,
        communityId: this.search.communityId,
        'phone': this.search.phone === '' ? null : this.search.phone
      }).then((res) => {
        if (res.status === 200) {
          _this.data = res.data.content
          _this.pagination.total = res.data.totalElements
          _this.$notification.success({
            message: res.message
          })
        } else {
          _this.$notification.warning({
            message: res.message
          })
        }
      });
    },
    onCommunityChange(value) {
      this.search.communityId = value[0];
    },
    changeAddMarketType(value) {
      console.log(value)
      this.newMarketState.marketInfo.typeId = value[0]
    },
    onAddCommunityChange(value) {
      this.newMarketState.marketInfo.communityId = value[0];
    },
    onUpdateCommunityChange(value) {
      console.log(value)
      this.updateMarket.info.communityId = value[0]

      console.log(this.updateMarket.info.communityId)
    },
    onUpdateTypeChange(value) {
      this.updateMarket.info.typeId = value[0]
    },
    async toUpdate() {
      let _this = this
      let array = this.updateMarket.info.feature.split(/,|，/);
      this.updateMarket.info.feature = JSON.stringify(array);
      await updateMarket(this.updateMarket.info).then(() => {
        this.updateMarket.state = false;
      }).catch((e) => {
        _this.$notification.error(e)
      })
      _this.handleTableChange()
    },

    allActive() {
      let _this = this;
      let aaa = 0;
      let length = this.selection.selectedId.length;
      new Promise((resolve, reject) => {
        for (let i = 0; i < length; i++) {
          updateMarket({id: this.selection.selectedId[i], state: 1}).finally(() => {
            aaa += 1;
            if (aaa === length) {
              resolve();
            }
          })
        }
      }).then(() => {
        _this.handleTableChange();
        _this.selection.selectedId = []
        _this.selection.selectedRowKeys = []
      })
    },
    allDisActive() {
      let _this = this;
      let aaa = 0;
      let length = this.selection.selectedId.length;
      new Promise((resolve, reject) => {
        for (let i = 0; i < length; i++) {
          updateMarket({id: this.selection.selectedId[i], state: 2}).finally(() => {
            aaa += 1;
            if (aaa == length) {
              resolve();
            }
          })
        }
      }).then(() => {
        _this.handleTableChange();
        _this.selection.selectedId = []
        _this.selection.selectedRowKeys = []
      })
    },
    allDelete() {
      let _this = this;
      let aaa = 0;
      let length = this.selection.selectedId.length;
      new Promise((resolve, reject) => {
        for (let i = 0; i < length; i++) {
          deleteMarket({id: this.selection.selectedId[i]}).finally(() => {
            aaa += 1;
            if (aaa == length) {
              resolve();
            }
          })
        }
      }).then(() => {
        _this.handleTableChange();
        _this.selection.selectedId = []
        _this.selection.selectedRowKeys = []
      })
    },

    onSelectChange(selectedRowKeys) {
      this.selection.selectedRowKeys = selectedRowKeys;
      this.selection.selectedId = [];
      for (let i = 0; i < selectedRowKeys.length; i++) {
        this.selection.selectedId.push(this.data[selectedRowKeys[i]].id)
      }

    },
    lookMarketInfo(record) {
      this.updateMarket.info = JSON.parse(JSON.stringify(record))
      this.updateMarket.info.communityId = this.updateMarket.info.community.id
      this.updateMarket.info.community = null
      this.updateMarket.info.typeId = this.updateMarket.info.type.id
      this.updateMarket.info.type = null
      this.updateMarket.info.user = null

      let strList = null
      let str = null
      try {
        strList = JSON.parse(this.updateMarket.info.feature)
        strList.forEach((val) => {
          if (str == null) str = val
          else str += ',' + val
        })
      } catch (e) {
        str = this.updateMarket.info.feature
      }
      this.updateMarket.info.feature = str
      this.updateMarket.state = true;
    },
    preToNewMarket() {
      this.newMarketState.marketInfo = {
        phone: '',
        address: '',
        communityId: '',
        typeId: '',
        contacts: ''
      }
      this.newMarketState.state = true;
    },
    async toNewMarket() {
      let _this = this
      await addMarket(this.newMarketState.marketInfo).then(() => {

        this.newMarketState.state = false;
      }).catch((e) => {
        _this.$notification.error(e)
      })
      _this.handleTableChange()
    }
  },
  computed: {
    hasSelected() {
      return this.selection.selectedRowKeys.length > 0;
    },
    updateMarketTypeName() {
      for (let i = 0; i < this.marketType.length; i++) {
        if (this.marketType[i].id == this.updateMarket.info.typeId) {
          return this.marketType[i].name
        }
      }
      return ''
    }
  }
}
</script>

<style scoped>

</style>